<template>
    <!-- pages/login/index.wxml -->
    <view class="login">
        <view class="login-container">
            <view class="login-img">
                <image src="../../static/assets/img/login.png" mode="widthFix"></image>
            </view>
            <view>
				<van-button class="btn-wechat" type="info" @tap.native="goLogin">一键授权</van-button>
            </view>
            <view class="login-btn">
                <van-button type="info" @tap.native="goLogin">手机号码登录/注册</van-button>
            </view>
            <view class="rule">
                <van-checkbox v-model="checked" @change="onChange" checked-color="#00BCAB"></van-checkbox>
                <view class="rule-konw">
                    我已经阅读并同意
                    <text @tap="showRule" style="color: #00bcab">《用户服务协议》</text>
                    、
                    <text @tap="showRule2" style="color: #00bcab">《隐私政策》</text>
                </view>
            </view>
            <van-popup round v-model="showRulePop" @close="closeRule">
                <view class="rules">
                    <view class="rule-title">用户服务协议</view>
                    <view class="rule-content">
                        <rich-text :nodes="userServe"></rich-text>
                    </view>
                    <view class="rule-line"></view>
                    <view class="rule-know" @tap="closeRule">我知道了</view>
                </view>
            </van-popup>
            <van-popup round v-model="showRulePop2" @close="closeRule2">
                <view class="rules">
                    <view class="rule-title">隐私政策</view>
                    <view class="rule-content">
                        <rich-text :nodes="userSecret"></rich-text>
                    </view>
                    <view class="rule-line"></view>
                    <view class="rule-know" @tap="closeRule2">我知道了</view>
                </view>
            </van-popup>
        </view>
    </view>
</template>

<script>
// pages/login/index.js
import util from './../../utils/util.js';
import api from './../../utils/api.js';
import config from './../../utils/config.js';
// import { zjLogin, noverifyLogin } from "@/api/zjzwLogin";
export default {
    data() {
        return {
            weixinCode: '',
            showRulePop: false,
            showRulePop2: false,
            userServe: config.userServe,
            userSecret: config.userSecret,
            checked: false
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad: function (options) {
        let that = this;
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {},
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    // onShareAppMessage: function() {}
    onReachBottom: function () {},
    /**
     * 用户点击右上角分享
     */ methods: {
		 setData:function(obj){
		 			let that = this;    
		 			let keys = [];    
		 			let val,data;    
		 			Object.keys(obj).forEach(function(key){    
		 			 keys = key.split('.');    
		 			 val = obj[key];    
		 			 data = that.$data;    
		 			 keys.forEach(function(key2,index){    
		 				 if(index+1 == keys.length){    
		 					 that.$set(data,key2,val);    
		 				 }else{    
		 					 if(!data[key2]){    
		 						that.$set(data,key2,{});    
		 					 }    
		 				 }    
		 				 data = data[key2];    
		 			 })    
		 			});    
		 			},
        onChange(event) {
            this.setData({
                checked: event
            });
        },

        /**
         * 关闭规则
         */
        closeRule() {
            this.setData({
                showRulePop: false // checked: true,
            });
        },

        closeRule2() {
            this.setData({
                showRulePop2: false // checked: true,
            });
        },

        showRule() {
			// console.log(111)
			// this.showRulePop=true;
            this.setData({
                showRulePop: true
            });
        },

        showRule2() {
            this.setData({
                showRulePop2: true
            });
        },

        goLogin() {
            if (!this.checked) {
                uni.showToast({
                    title: '请勾选同意《用户服务协议》、《隐私政策》',
                    icon: 'none'
                });
                return;
            }
		let param = {loginName:uni.getStorageSync('phoneNumber')};//getMoblie()  "18658195007"
		uni.showLoading({
		    title: '加载中...'
		});
		util.request(api.noverifyLogin, param, 'POST', 'application/x-www-form-urlencoded')
		    .then((result) => {
		        uni.hideLoading({
		            success: (res) => {}
		        });
		if (result.success) {
			uni.setStorageSync("AUTHORIZATION",result.data.busiInfo.token);
		  uni.setStorageSync("status", true); //状态
		  uni.setStorageSync(
		    "phoneNumber",
		    result.data.busiInfo.phoneNumber,
		    // 7 * 24 * 60 * 60 * 1000
		  ); //手机号
		  uni.setStorageSync(
		    "name",
		    result.data.busiInfo.name,
		    // 7 * 24 * 60 * 60 * 1000
		  ); //姓名
		  uni.setStorageSync(
		    "plateNos",
		    result.data.busiInfo.plateNos!=null&&result.data.busiInfo.plateNos.length>0&&result.data.busiInfo.plateNos.map((e) => e).toString() || "",
		    // 7 * 24 * 60 * 60 * 1000
		  ); //用户车牌号
		  uni.setStorageSync(
		    "faceImageUrl",
		    result.data.busiInfo.faceImageUrl,
		    // 7 * 24 * 60 * 60 * 1000
		  ); //头像
		  uni.setStorageSync(
		    "authorization",
		    result.data.busiInfo.token,
		    // 7 * 24 * 60 * 60 * 1000
		  ); //token
		  // alert(Vue.ls.get("authorization"))
		  uni.setStorageSync(
		    "identityId",
		    result.data.busiInfo.identityId,
		    // 7 * 24 * 60 * 60 * 1000
		  ); //用户id
		  uni.setStorageSync(
		    "unionId",
		    result.data.busiInfo.unionId,
		    // 7 * 24 * 60 * 60 * 1000
		  ); //用户unionId
		  // console.log(uni.getStorageSync('identityId');) 
		  // uni.navigateTo({
		  //     url: '../index2/index'
		  // });
		  uni.switchTab({
		  	url: '../home/index'
		  })
		  // this.$router.push({path:'/home'})
		}
		    })
		    .catch((err) => {
		        uni.showToast({
		            title: err || '接口出错了，请稍后再试',
		            icon: 'none'
		        });
		    });
            // uni.navigateTo({
            //     url: '../phone/index'
            // });
        },

        getPhoneNumber(e) {
            if (!this.checked) {
                uni.showToast({
                    title: '请勾选同意《用户服务协议》、《隐私政策》',
                    icon: 'none'
                });
                return;
            }

            if (e.detail.errMsg == 'getPhoneNumber:ok') {
                let param = {
                    code: this.weixinCode
                };

                if (uni.getStorageSync('shareId')) {
                    param.originUnionId = uni.getStorageSync('shareId') || '';
                }

                if (uni.getStorageSync('activityCode')) {
                    param.activityCode = uni.getStorageSync('activityCode') || '';
                }

                uni.showLoading({
                    title: '加载中'
                });
                util.request(api.wxLogin, param, 'POST')
                    .then((res) => {
                        if (res.success) {
                            //有openid直接进首页前也要判断有无车牌
                            uni.hideLoading();
                            uni.setStorage({
                                key: 'AUTHORIZATION',
                                data: res.data.busiInfo.token
                            }); //token

                            this.setStorages(res); //开始存储所需要的信息
                        } else {
                            //无openid去绑定,有车牌直接进首页，无则进修改页---没有车牌也暂时跳过去首页
                            uni.setStorage({
                                key: 'AUTHORIZATION',
                                data: res.data.busiInfo.token
                            });
                            uni.setStorage({
                                key: 'openId',
                                data: res.data.busiInfo.openId
                            }); //openId

                            const wechatUnionId = res.wechatUnionId;
                            let param = {
                                nikeName: '用户_' + util.randomWord(),
                                openId: res.data.busiInfo.openId,
                                url: '',
                                encryptedData: e.detail.encryptedData,
                                iv: e.detail.iv,
                                wechatUnionId: wechatUnionId
                            }; // 如果从分享进来注册的，还需要加上分享人的参数

                            if (uni.getStorageSync('shareId')) {
                                param.originUnionId = uni.getStorageSync('shareId') || '';
                            }

                            if (uni.getStorageSync('activityCode')) {
                                param.activityCode = uni.getStorageSync('activityCode') || '';
                            }

                            util.request(api.wxBind, param, 'POST')
                                .then((resp) => {
                                    if (resp.success) {
                                        uni.hideLoading();
                                        uni.removeStorageSync('shareId'); //移除掉分享者id缓存

                                        uni.setStorage({
                                            key: 'AUTHORIZATION',
                                            data: resp.data.busiInfo.token
                                        }); //token

                                        this.setStorages(resp);
                                    } else {
                                        uni.hideLoading();
                                        uni.showToast({
                                            title: resp.msg || '接口出错了，请重试',
                                            icon: 'none'
                                        });
                                        let that = this;
                                        uni.login({
                                            success(res) {
                                                that.setData({
                                                    weixinCode: res.code
                                                });
                                            }
                                        });
                                    }
                                })
                                .catch((err) => {
                                    uni.hideLoading();
                                    uni.showToast({
                                        title: '接口出错了，请重试',
                                        icon: 'none'
                                    });
                                    let that = this;
                                    uni.login({
                                        success(res) {
                                            that.setData({
                                                weixinCode: res.code
                                            });
                                        }
                                    });
                                });
                        }
                    })
                    .catch((err) => {
                        uni.hideLoading();
                        let that = this;
                        uni.login({
                            success(res) {
                                that.setData({
                                    weixinCode: res.code
                                });
                            }
                        });
                        uni.showToast({
                            title: '接口出错了，请重试',
                            icon: 'none'
                        });
                    });
            }
        },

        /***缓存参数 */
        setStorages(res) {
            uni.setStorage({
                key: 'name',
                data: res.data.busiInfo.name
            }); //姓名

            uni.setStorage({
                key: 'phoneNumber',
                data: res.data.busiInfo.phoneNumber
            }); //手机号

            uni.setStorage({
                key: 'faceImageUrl',
                data: res.data.busiInfo.faceImageUrl
            }); //头像

            uni.setStorage({
                key: 'identityId',
                data: res.data.busiInfo.identityId
            }); //用户id

            uni.setStorage({
                key: 'unionId',
                data: res.data.busiInfo.unionId
            }); //用户id

            if (res.data.busiInfo.plateNos != null && res.data.busiInfo.plateNos.length > 0) {
                uni.setStorage({
                    key: 'status',
                    data: true
                }); //状态

                uni.setStorage({
                    key: 'plateNos',
                    data: res.data.busiInfo.plateNos.map((e) => e).toString()
                }); //用户车牌号
                // v2.5.4新加的访客链接进入时的逻辑

                if (uni.getStorageSync('visitor_code')) {
                    uni.redirectTo({
                        url: '../newBookpark/newBookpark?param=' + uni.getStorageSync('visitor_parkcode')
                    });
                } else {
                    uni.switchTab({
                        url: uni.getStorageSync('lastPagePath') ? uni.getStorageSync('lastPagePath') : '../home/index'
                    });
                }
            } else {
                uni.setStorage({
                    key: 'status',
                    data: true
                }); //状态

                uni.setStorage({
                    key: 'plateNos',
                    data: ''
                }); //用户车牌号
                // v2.5.4新加的访客链接进入时的逻辑

                if (uni.getStorageSync('visitor_code')) {
                    uni.redirectTo({
                        url: '../addLicense/addLicense'
                    });
                } else {
                    uni.switchTab({
                        url: uni.getStorageSync('lastPagePath') ? uni.getStorageSync('lastPagePath') : '../home/index'
                    });
                }
            }
        }
    }
};
</script>
<style>
@import './index.css';
</style>
